package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.util.URIUtil;
import cn.edu.nju.ws.sview.views.Entity;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;


public class RecommendServlet extends HttpServlet {
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		String jsonstr = request.getParameter("getRecommends");
		if(jsonstr != null){
			String str = URLDecoder.decode(jsonstr, "utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String type_str = (String)regtJSON.get("type_str");
			int id = Integer.parseInt((String)regtJSON.get("id"));
//			int type_int = ((Long)regtJSON.get("type_int")).intValue();
//			int id = ((Long)regtJSON.get("id")).intValue();
			String lang = (String)regtJSON.get("lang");
			int length = ((Long)regtJSON.get("length")).intValue();
			
			int type_int = URIUtil.getItemTypeInt(type_str);
			
			
			ArrayList<LinkedList<QuadItem>> recommends = EntityBrowsing.getRecommendEntity(type_int, id, lang, length);
			String[] recomdName = {"byHistory","byRelated"};
			JSONObject result = new JSONObject();
			for(int i=0; i<recommends.size()&&i<recomdName.length; i++){
				JSONArray array = new JSONArray();
				LinkedList<QuadItem> list = recommends.get(i);
				for(QuadItem item : list){
					JSONObject jsob = new JSONObject();
					jsob.put("genre", item.getGenre());
					jsob.put("id", item.getId());
					String name = item.getName();
					if (item.getGenre() == Entity.URI_ENTITY && name.equals("")) {
						if (lang.equals("en")) {
							try {
								name = URIUtil.getLocalname(URIIDCache
										.getInstance().getURI(item.getId()));
							} catch (Throwable e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							continue;
						}
					}
					jsob.put("name", name);
//					JSONArray types = new JSONArray();
//					ArrayList<Entry<Integer, String>> typeArray = item.getTypes();
//					for (Entry<Integer, String> mapItem : typeArray) {
////						System.out.println("type_id"+mapItem.getKey()+"|label:"+mapItem.getValue());
//						JSONObject tob = new JSONObject();
//						tob.put("label", mapItem.getValue());
//						tob.put("type_id", mapItem.getKey());
//						types.add(tob);
//					}
//					jsob.put("type", types);
					array.add(jsob);
				}
				result.put(recomdName[i], array);
			}//end of for i
			result.put("status", "ok");
			System.out.println(type_int+"|"+id+"|"+lang+"|"+length+"|recommend:"+result.toJSONString());
			String result_str = URLEncoder.encode(result.toJSONString(),"utf-8").replace("+", "%20");//for chinese messy code
			response.getWriter().print(result_str);
		}else{
			JSONObject result = new JSONObject();
			result.put("status", "No parameter");
			response.getWriter().print(result);
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		doGet(request, response);
	}

}
